import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../core/di/service_locator.dart';
import '../../../core/exceptions/exception_handler.dart';
import '../../../data/models/upload/upload_task.dart';
import '../../../domain/providers/upload_queue_provider.dart';
import '../../../domain/services/upload_task_factory.dart';

/// 上传页面
class UploadScreen extends StatelessWidget {
  const UploadScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('文件上传'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              Provider.of<UploadQueueProvider>(
                context,
                listen: false,
              ).clearCompletedTasks();
            },
            tooltip: '清除已完成',
          ),
        ],
      ),
      body: Column(
        children: [
          // 上传按钮区域
          _buildUploadButtons(context),

          // 上传任务列表
          Expanded(
            child: Consumer<UploadQueueProvider>(
              builder: (context, provider, _) {
                if (provider.tasks.isEmpty) {
                  return const Center(child: Text('暂无上传任务，请选择文件上传'));
                }

                return ListView.builder(
                  itemCount: provider.tasks.length,
                  itemBuilder: (context, index) {
                    final task = provider.tasks[index];
                    return _buildTaskItem(context, task, provider);
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建上传按钮区域
  Widget _buildUploadButtons(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          ElevatedButton.icon(
            icon: const Icon(Icons.upload_file),
            label: const Text('选择文件'),
            onPressed: () => _pickAndUploadFiles(context),
          ),
          ElevatedButton.icon(
            icon: const Icon(Icons.folder),
            label: const Text('选择文件夹'),
            onPressed: () {
              // TODO: 实现文件夹上传
            },
          ),
        ],
      ),
    );
  }

  /// 构建任务列表项
  Widget _buildTaskItem(
    BuildContext context,
    UploadTask task,
    UploadQueueProvider provider,
  ) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 文件名和状态
            Row(
              children: [
                Expanded(
                  child: Text(
                    task.fileName,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                _buildStatusChip(task.status),
              ],
            ),

            const SizedBox(height: 8),

            // 文件大小和进度
            Row(
              children: [
                Text(
                  '${_formatFileSize(task.fileSize)} | ${task.type == UploadTaskType.chunkFile ? '分片上传' : '普通上传'}',
                ),
                const Spacer(),
                Text('${(task.progress * 100).toStringAsFixed(1)}%'),
              ],
            ),

            const SizedBox(height: 8),

            // 进度条
            LinearProgressIndicator(value: task.progress),

            const SizedBox(height: 8),

            // 操作按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                if (task.status == UploadTaskStatus.uploading)
                  IconButton(
                    icon: const Icon(Icons.pause),
                    onPressed: () => provider.pauseTask(task.id),
                    tooltip: '暂停',
                  ),

                if (task.status == UploadTaskStatus.paused)
                  IconButton(
                    icon: const Icon(Icons.play_arrow),
                    onPressed: () => provider.resumeTask(task.id),
                    tooltip: '恢复',
                  ),

                if (task.status == UploadTaskStatus.failed)
                  IconButton(
                    icon: const Icon(Icons.refresh),
                    onPressed: () => provider.retryTask(task.id),
                    tooltip: '重试',
                  ),

                if (task.status == UploadTaskStatus.pending ||
                    task.status == UploadTaskStatus.uploading)
                  IconButton(
                    icon: const Icon(Icons.cancel),
                    onPressed: () => provider.cancelTask(task.id),
                    tooltip: '取消',
                  ),

                if (task.status == UploadTaskStatus.failed)
                  IconButton(
                    icon: const Icon(Icons.info_outline),
                    onPressed: () => _showErrorDialog(context, task),
                    tooltip: '查看错误',
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建状态标签
  Widget _buildStatusChip(UploadTaskStatus status) {
    Color color;
    String label;

    switch (status) {
      case UploadTaskStatus.pending:
        color = Colors.blue;
        label = '等待中';
        break;
      case UploadTaskStatus.uploading:
        color = Colors.orange;
        label = '上传中';
        break;
      case UploadTaskStatus.paused:
        color = Colors.amber;
        label = '已暂停';
        break;
      case UploadTaskStatus.completed:
        color = Colors.green;
        label = '已完成';
        break;
      case UploadTaskStatus.failed:
        color = Colors.red;
        label = '失败';
        break;
      case UploadTaskStatus.cancelled:
        color = Colors.grey;
        label = '已取消';
        break;
    }

    return Chip(
      label: Text(
        label,
        style: const TextStyle(color: Colors.white, fontSize: 12),
      ),
      backgroundColor: color,
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0),
      visualDensity: VisualDensity.compact,
    );
  }

  /// 选择并上传文件
  Future<void> _pickAndUploadFiles(BuildContext context) async {
    try {
      final uploadTaskFactory = serviceLocator<UploadTaskFactory>();
      final tasks = await uploadTaskFactory.createUploadTasksFromPicker(
        directoryId: 0, // 上传到根目录
      );

      if (tasks.isNotEmpty) {
        await Provider.of<UploadQueueProvider>(
          context,
          listen: false,
        ).addTasks(tasks);
      }
    } catch (e) {
      ExceptionHandler.handleException(context, e);
    }
  }

  /// 显示错误对话框
  void _showErrorDialog(BuildContext context, UploadTask task) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('上传失败'),
            content: Text(task.errorMessage ?? '未知错误'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('关闭'),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  Provider.of<UploadQueueProvider>(
                    context,
                    listen: false,
                  ).retryTask(task.id);
                },
                child: const Text('重试'),
              ),
            ],
          ),
    );
  }

  /// 格式化文件大小
  String _formatFileSize(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
    }
  }
}
